package dragon.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dragon.core.exception.ExceptionHandler;
import ejw.RequestHandler;
import ejw.ServerInterface;
import ejw.ServerInterface.MultipartFormData;
import ejw.WebAppException;

public class Handler extends RequestHandler {

	public String successString = "success";
	
	public String failString = "fail";
	/**
	 * 空的JSON返回值
	 */
	public String emptyJSON = "{}";

	/**
	 * 默认的成功JSON返回值
	 */
	public String successJSON = "{\"result\":true}";

	/**
	 * 默认的失败JSON返回值
	 */
	public String failureJSON = "{\"result\":false,\"MESSAGE_ERROR\":\"\",\"MESSAGE_WARNING\":\"\",\"MESSAGE_INFO\":\"\"}";

	/**
	 * 获取项目名
	 * 
	 * @return
	 */
	public String getContextPath() {
		HttpServletRequest request = getServletRequest();
		String path = request.getContextPath();
		request = null;
		return path;
	}

	/**
	 * 获取项目根路径
	 * 
	 * @return
	 */
	public String getBasePath() {
		HttpServletRequest request = getServletRequest();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		request = null;
		return basePath;
	}

	/**
	 * 获取参数
	 * 
	 * @param parameter
	 *            参数名
	 * @return
	 */
	@Override
	public String getParameter(String parameter) {
		ServerInterface sif = getServerInterface();
		String result = sif.getParameter(parameter);
		if( result != null )
			result = result.trim();
		return result;
	}

	/**
	 * 获取所有参数
	 * 
	 * @return Map<String,String>,k:参数名,v:参数值
	 * @throws ExceptionHandler
	 */
	public Map<String, String> getParameterMap() throws ExceptionHandler {
		ServerInterface sif = getServerInterface();
		if (!sif.isMultipartFormData()) {
			return getNormalParameterMap(sif);
		} else {
			return getMultipartParameterMap(sif);
		}
	}

	/**
	 * 获取普通表单参数
	 * 
	 * @param sif
	 * @return
	 */
	private Map<String, String> getNormalParameterMap(ServerInterface sif) {
		Map<String, String> result = new HashMap<String, String>();
		List<String> parameternames = sif.getParameterNames();
		String[] values = null;
		StringBuilder value = new StringBuilder();
		for (String parameter : parameternames) {
			if (value.length() > 0) {
				value.delete(0, value.length());
			}
			values = sif.getParameters(parameter);
			if (values != null) {
				for (int i = 0; i < values.length; i++) {
					if (values[i] != null && !StringUtils.isEmpty(values[i])) {
						value.append(values[i].trim()).append(",");
					}
				}
				if (value.length() > 0) {
					value.delete(value.length() - 1, value.length());
				}
			}
			result.put(parameter, value.toString());
		}
		return result;
	}

	/**
	 * 获取 multipart 表单参数
	 * 
	 * @param sif
	 * @return
	 * @throws ExceptionHandler
	 */
	@SuppressWarnings("unchecked")
	private Map<String, String> getMultipartParameterMap(ServerInterface sif) throws ExceptionHandler {
		sif.loadMultipartFormData();

		Map<String, String> result = new HashMap<String, String>();
		List<String> parameternames = sif.getParameterNames();
		result.put("bizCode", sif.getParameter("bizCode"));
		List<MultipartFormData> mfds = null;
		MultipartFormData mfd = null;
		Object obj = null;
		for (String parameter : parameternames) {
			if ("bizCode".equals(parameter)) {
				continue;
			}
			obj = sif.getMultipartFormData2(parameter);
			if (obj == null) {
				continue;
			}
			if (obj instanceof MultipartFormData) {
				// 单值类型
				mfd = (MultipartFormData) obj;
				getParameter(sif, result, parameter, mfd);
			} else {
				// 多值类型
				mfds = (List<MultipartFormData>) obj;
				for (MultipartFormData _mfd : mfds) {
					getParameter(sif, result, parameter, _mfd);
				}
			}
		}
		obj = null;
		mfd = null;
		mfds = null;
		parameternames = null;
		sif = null;
		return result;
	}

	/**
	 * 获取参数
	 * 
	 * @param sif
	 * @param result
	 * @param parameter
	 * @param mfd
	 * @throws ExceptionHandler
	 */
	private void getParameter(ServerInterface sif, Map<String, String> result, String parameter, MultipartFormData mfd) throws ExceptionHandler {
		String value = null;
		String oldValue = null;
		boolean hasFile = false;
		int FILENUM_INDEX = -1;

		if (mfd.isFormField()) {
			// 普通字段
			try {
				value = mfd.getString(sif.getServletRequest().getCharacterEncoding());// mulltipart模式下不能用ServerInterface.getParameter(parameter);ServerInterface.getParameters(parameter);
			} catch (WebAppException e) {
				throw new ExceptionHandler(e);
			}
			// mfd.delete();//删除临时文件，以 multipart 方式提交表单，每个字段都会默认当成文件进行处理
		} else {
			// 文件字段
			if (mfd.getSize() > 0) {
				hasFile = true;
				// 保存文件
				value = FileHandler.save(result.get("bizCode"), mfd);

				// 对于File类型的字段，input的id和name构成形式为 field.code.toUpperCase+_FILENUM_{index}，所以需要计算真实的参数名
				FILENUM_INDEX = parameter.indexOf("_FILENUM_");
				if (FILENUM_INDEX != -1) {
					parameter = parameter.substring(0, FILENUM_INDEX);
				}
			} else {
				// mfd.delete();
			}
		}

		if (value != null) {
			oldValue = result.get(parameter);
			if (oldValue == null || StringUtils.isEmpty(oldValue)) {
				result.put(parameter, value);
			} else {
				if (!StringUtils.isEmpty(value)) {
					result.put(parameter, oldValue + "," + value);
				}
			}

			// 记录新增的文件
			if (hasFile) {
				parameter = parameter + "_NEWFILE";
				oldValue = result.get(parameter);
				if (oldValue == null || StringUtils.isEmpty(oldValue)) {
					result.put(parameter, value);
				} else {
					if (!StringUtils.isEmpty(value)) {
						result.put(parameter, oldValue + "," + value);
					}
				}
			}
		}

	}

	/**
	 * 获取Request域属性
	 * 
	 * @param attributeName
	 *            属性名称
	 * @return
	 */
	public <T> T getAttribute(String attributeName) {
		ServerInterface sif = getServerInterface();
		return sif.getAttribute(attributeName);
	}

	/**
	 * 设置Request域属性
	 * 
	 * @param attributeName
	 *            属性名称
	 * @param attributeValue
	 *            属性值
	 */
	public void setAttribute(String attributeName, Object attributeValue) {
		ServerInterface sif = getServerInterface();
		sif.setAttribute(attributeName, attributeValue);
		sif = null;
	}

	/**
	 * 获取Session域属性
	 * 
	 * @param attributeName
	 *            属性名称
	 * @return
	 */
	public <T> T getSessionAttribute(String attributeName) {
		ServerInterface sif = getServerInterface();
		return sif.getSessionAttribute(attributeName);
	}

	/**
	 * 设置Session域属性
	 * 
	 * @param attributeName
	 *            属性名称
	 * @param attributeValue
	 *            属性值
	 */
	public void setSessionAttribute(String attributeName, Object attributeValue) {
		ServerInterface sif = getServerInterface();
		sif.setSessionAttribute(attributeName, attributeValue);
		sif = null;
	}

	/**
	 * 获取Application作用域的属性
	 * 
	 * @param attributeName
	 *            属性名
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getApplicationAttribute(String attributeName) {
		return (T) getServerInterface().getServletRequest().getSession().getServletContext().getAttribute(attributeName);
	}

	/**
	 * 设置Application作用域的属性
	 * 
	 * @param attributeName
	 *            属性名称
	 * @param attributeValue
	 *            属性值
	 */
	public void setApplicationAttribute(String attributeName, Object attributeValue) {
		getServerInterface().getServletRequest().getSession().getServletContext().setAttribute(attributeName, attributeValue);
	}

	/**
	 * 向客户端输出内容
	 * 
	 * @param result
	 *            待输出内容
	 * @throws ExceptionHandler
	 */
	public void output(Object result) throws ExceptionHandler {
		ServerInterface sif = getServerInterface();
		HttpServletResponse response = sif.getServletResponse();
		response.setCharacterEncoding("UTF-8");
		try {
			response.getWriter().write(result.toString());
		} catch (IOException e) {
			throw new ExceptionHandler(e);
		}
	}

	/**
	 * 跳转到指定页面
	 * 
	 * @param target
	 * @throws ExceptionHandler
	 */
	public void sendRedirect(String target) throws ExceptionHandler {
		ServerInterface sif = getServerInterface();
		HttpServletResponse response = sif.getServletResponse();
		try {
			response.sendRedirect(target);
		} catch (IOException e) {
			throw new ExceptionHandler(e);
		}
		response = null;
		sif = null;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileName
	 *            文件名
	 * @param filePath
	 *            文件路径
	 * @throws ExceptionHandler
	 */
	public void downloadFile(String fileName, String filePath) throws ExceptionHandler {
		File file = new File(FilePath.FILEUPLOAD + filePath);
		if (!file.exists()) {
			throw new ExceptionHandler("未发现资源！");
		}
		ServerInterface sif = getServerInterface();
		HttpServletResponse response = sif.getServletResponse();
		try {
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			response.addHeader("Content-Length", "" + file.length());

			ServletOutputStream os = response.getOutputStream();
			InputStream is = new FileInputStream(file);
			byte[] b = new byte[256];
			int len = -1;
			while ((len = is.read(b)) != -1) {
				os.write(b, 0, len);
			}
			is.close();
			os.flush();
			os.close();
		} catch (IOException e) {
			throw new ExceptionHandler(e);
		}
		response = null;
		sif = null;
	}


}
